package demo

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

func Binding() {
	Router := gin.Default()
	//查询参数绑定
	Router.GET("/bindingQuery", func(c *gin.Context) {
		//查询参数绑定
		type User struct {
			Name string `form:"name"`
			Age  int    `form:"age"`
		}
		var user User
		err := c.ShouldBindQuery(&user)
		if err != nil {
			c.JSON(200, gin.H{
				"msg": "查询参数绑定失败",
			})
			return
		}
		fmt.Println(user)
	})
	//路径参数绑定
	Router.POST("/bind/:age/:name", func(ctx *gin.Context) {
		type User struct {
			Age  int    `uri:"age"`
			Name string `uri:"name"`
		}
		var user User
		err := ctx.ShouldBindUri(&user)
		if err != nil {
			ctx.JSON(200, gin.H{
				"msg": "表单参数绑定失败",
			})
			return
		}
		fmt.Println(user)
	})

	//表单参数绑定
	Router.POST("/bindingForm", func(c *gin.Context) {
		//表单参数绑定
		type User struct {
			Name string `form:"name"`
			Age  int    `form:"age"`
		}
		var user User
		err := c.ShouldBind(&user)
		if err != nil {
			c.JSON(200, gin.H{
				"msg": "表单参数绑定失败",
			})
		}
		fmt.Println(user)
	})

	//json参数绑定
	Router.POST("/bindingJson", func(c *gin.Context) {
		type User struct {
			Name string `json:"name"`
			Age  int    `json:"age"`
		}
		var user User
		err := c.ShouldBindJSON(&user)
		if err != nil {
			c.JSON(200, gin.H{
				"msg": "json参数绑定失败",
			})
		}
		fmt.Println(user)
	})

	//请求头
	Router.POST("/header", func(c *gin.Context) {
		type User struct {
			Name        string `header:"Name"`
			Age         int    `header:"Age"`
			ContentType string `header:"Content-Type"`
		}
		var user User
		err := c.ShouldBindHeader(&user)
		if err != nil {
			c.JSON(200, gin.H{
				"msg": "json参数绑定失败",
			})
		}
		fmt.Println(user)
	})

	Router.Run(":8080")
}
